package cs236369.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Logging.Monitor;

import cs236369.webserver.classes.CreateClass;
import cs236369.webserver.typehandler.Session;
import cs236369.webserver.typehandler.TypeHandler;

import javassist.*;

public class TSPEngine implements TypeHandler {

	private Properties p;
	
	public TSPEngine(Properties p) {
		this.p = p;
	}
	
	@Override
	public void handle(	File file, Map<String, String> parameters,
						PrintStream out, Session session) {

		Monitor.write(this, "Handling the dynamic file");
		String filePath = file.getPath();
		File workingFile = new File(filePath);
		Scanner scanner;
		
		try {
			scanner = new Scanner(workingFile);
			scanner.useDelimiter("<\\?(([^\\?>])+((\\?*)|(>*)))*\\?>");
			Pattern pattern = scanner.delimiter();
			BufferedReader reader = new BufferedReader(new FileReader(workingFile));
			
			String tspFileContent = "";
			String line = null;
			while((line = reader.readLine()) != null) {
				tspFileContent += line;
			}
			
			Matcher matcher = pattern.matcher(tspFileContent);
			ArrayList<String> codes = new ArrayList<String>();
			while(matcher.find()){
				codes.add(matcher.group());
			}
			
			workingFile = new File(filePath);
			scanner = new Scanner(workingFile);
			scanner.useDelimiter("<\\?(([^\\?>])+((\\?*)|(>*)))*\\?>");
			ArrayList<String> htmls = new ArrayList<String>();
			while(scanner.hasNext()){
				htmls.add(scanner.next());
			}
			
			String code = generateJavaCode(htmls, codes);
			Monitor.write(this, "Recieved this code:"+code);
			CreateClass generatedClass = new CreateClass(
											p.getProperty("jre-path"), 
											"TSPEngnine" + System.currentTimeMillis());
			generatedClass.addCommandToMethod(code);
			generatedClass.addMethod();
			generatedClass.activateMehod(parameters, out, session);
			
		} catch (Exception e) {
			 String msg = 	"An error has occured while handling the request. " +
			 				"Because of:\n"+e;
			 Monitor.write(this,msg);
			 System.err.println(msg);
			 throw new RuntimeException(msg);
		}
	}
	
	private String generateJavaCode(ArrayList<String> htmls, ArrayList<String> codes){
		String code = "";
		int i = 0;
		for(String s : htmls) {
			Monitor.write(this, s);
			String[] strings = s.split("\n");
			for(String str:strings) {
				str = str.replaceAll("\\\"", "\\\\\"");
				code += "out.print(\"" + str + "\\n" + "\");";
			}
			if (i < codes.size()) {
				code += codes.get(i).substring(2,codes.get(i).length()-2);
				code += "\n";
				i++;
			}
		} 
		return code;
	}
	
}
